#include "string.h"

char& ywx::string::operator[](size_t pos)
{
	return _str[pos];
}

const char& ywx::string::operator[](size_t pos) const
{
	return _str[pos];
}

void ywx::string::reserve(size_t n)
{
	if (n > _capacity)
	{
		char* tmp = new char[n + 1];
		strcpy(tmp, _str);
		delete[] _str;
		_str = tmp;
		_capacity = n;
	}
}

void ywx::string::push_back(char ch)
{
	if (_size == _capacity)
	{
		reserve(_capacity == 0 ? 4 : 2 * _capacity);
	}

	_str[_size] = ch;
	++_size;
	_str[_size] = '\0';
}

ywx::string& ywx::string::append(const string& str)
{
	int len = strlen(str._str);
	while (_size + len > _capacity)
	{
		reserve(_capacity == 0 ? 4 : 2 * _capacity);
	}
	for (int i = 0; i < len; i++)
	{
		_str[_size] = str[i];
		_size++;
	}
	++_size;
	_str[_size] = '\0';
	return *this;
}

ywx::string& ywx::string::operator+=(const char c)
{
	push_back(c);
	return *this;
}

ywx::string& ywx::string::operator+=(const char* str)
{
	append(str);
	return *this;
}

size_t ywx::string::npos = -1;
